package com.back.service.impl;

import com.back.mapper.AnswerRecordsMapper;
import com.back.model.dto.DoAnswerDTO;
import com.back.model.dto.SubmitQuestionDTO;
import com.back.model.dto.UserAnswerDTO;
import com.back.model.entity.AnswerRecords;
import com.back.model.vo.QuestionsVo;
import com.back.utils.JacksonUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.back.model.entity.ExamRecords;
import com.back.service.ExamRecordsService;
import com.back.mapper.ExamRecordsMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
* @author Administrator
* @description 针对表【exam_records(考试记录表)】的数据库操作Service实现
* @createDate 2025-08-21 17:00:58
*/
@Service
public class ExamRecordsServiceImpl extends ServiceImpl<ExamRecordsMapper, ExamRecords>
    implements ExamRecordsService{

    @Resource
    private ExamRecordsMapper examRecordsMapper;
    @Resource
    private AnswerRecordsMapper answerRecordsMapper;

    @Override
    public Long saveRecoreds(DoAnswerDTO doAnswerDTO,List<QuestionsVo> questionsVoList) {

        ExamRecords examsRecords = new ExamRecords();
        examsRecords.setUserId(doAnswerDTO.getUserId());
        examsRecords.setExamId(doAnswerDTO.getQueryId());
        examRecordsMapper.insert(examsRecords);

        AnswerRecords answerRecords = new AnswerRecords();
        answerRecords.setExamRecordId(examsRecords.getId());
        answerRecords.setUserId(doAnswerDTO.getQueryId());
        answerRecords.setQuestioncontext(JacksonUtils.objectToJson(questionsVoList));
        answerRecordsMapper.insert(answerRecords);

        return examsRecords.getId();
    }

    @Override
    public void updateRecoreds(BigDecimal divide, SubmitQuestionDTO submitQuestionDTO, List<QuestionsVo> questionsVos ) {
        Long userId = submitQuestionDTO.getUserId();
        Long examsRecordId = submitQuestionDTO.getExamsRecordId();
        ExamRecords examsRecords = new ExamRecords();
        examsRecords.setId(examsRecordId);
        examsRecords.setTotalScore(divide);
        examRecordsMapper.updateById(examsRecords);

        LambdaQueryWrapper<AnswerRecords> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AnswerRecords::getExamRecordId,examsRecords.getId());
        queryWrapper.eq(AnswerRecords::getUserId,userId);
        AnswerRecords answerRecords = new AnswerRecords();
        answerRecords.setQuestioncontext(JacksonUtils.objectToJson(questionsVos));
        answerRecords.setScore(divide);
        answerRecordsMapper.update(answerRecords,queryWrapper);
    }
}




